package com.figo.player

import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FigoPlayerPlugin */
class FigoPlayerPlugin: FlutterPlugin, MethodCallHandler {
  private lateinit var channel : MethodChannel
  private var playerEngine: PlayerEngine? = null

  companion object {
    init {
      System.loadLibrary("figo_player_plugin")
    }
  }

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "figo_player_plugin/engine")
    channel.setMethodCallHandler(this)
    playerEngine = PlayerEngine()
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when (call.method) {
      "loadMedia" -> {
        val filePath = call.argument<String>("filePath")
        val config = call.argument<Map<String, Any>>("config")
        val success = playerEngine?.loadMedia(filePath, config) ?: false
        result.success(success)
      }
      "play" -> {
        val success = playerEngine?.play() ?: false
        result.success(success)
      }
      "pause" -> {
        val success = playerEngine?.pause() ?: false
        result.success(success)
      }
      "stop" -> {
        val success = playerEngine?.stop() ?: false
        result.success(success)
      }
      "seek" -> {
        val time = call.argument<Double>("time") ?: 0.0
        val success = playerEngine?.seek(time) ?: false
        result.success(success)
      }
      "setVolume" -> {
        val volume = call.argument<Double>("volume") ?: 1.0
        playerEngine?.setVolume(volume)
        result.success(null)
      }
      "setHardwareDecode" -> {
        val enable = call.argument<Boolean>("enable") ?: false
        playerEngine?.setHardwareDecode(enable)
        result.success(null)
      }
      "setBatteryOptimization" -> {
        val enable = call.argument<Boolean>("enable") ?: false
        playerEngine?.setBatteryOptimization(enable)
        result.success(null)
      }
      "setMemoryLimit" -> {
        val mbLimit = call.argument<Int>("mbLimit") ?: 100
        playerEngine?.setMemoryLimit(mbLimit)
        result.success(null)
      }
      else -> result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
    playerEngine?.dispose()
    playerEngine = null
  }
}

